package com.fzdy.dataplatform.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fzdy.dataplatform.controller.api.DelArr;
import com.fzdy.dataplatform.controller.api.ModuleCallback;
import com.fzdy.dataplatform.controller.api.sysLog.LogStringUtil;
import com.fzdy.dataplatform.controller.api.sysLog.SysLogApi;
import com.fzdy.dataplatform.controller.api.user.UserEditApi;
import com.fzdy.dataplatform.controller.api.user.UserGetApi;
import com.fzdy.dataplatform.controller.api.user.UserListApi;
import com.fzdy.dataplatform.core.common.AjaxCallback;
import com.fzdy.dataplatform.core.common.Check;
import com.fzdy.dataplatform.core.common.TimeStampTool;
import com.fzdy.dataplatform.core.controller.BaseController;
import com.fzdy.dataplatform.core.vo.Page;
import com.fzdy.dataplatform.entity.Role;
import com.fzdy.dataplatform.entity.User;
import com.fzdy.dataplatform.service.RoleService;
import com.fzdy.dataplatform.service.UserService;
import com.fzdy.dataplatform.webutil.MD5ArithmeticUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping(value = "/sysmanage/user")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @RequestMapping(value = "/list")
    public String list(@RequestBody Page<User> page, HttpServletRequest request) {
        AjaxCallback ajaxCallback;
        User user = new User();
        user.setName(page.getName());
        user.setStatus(1);
        userService.getPageByExampleLike(user, page);
        ajaxCallback = new AjaxCallback(userdbtoapi(page.getList()), page.getTotalRow());
        return JSON.toJSONString(ajaxCallback);
    }

    @RequestMapping(value = "/edit")
    public String edit(@RequestBody UserEditApi api, HttpServletRequest request) {
        User user=webUtilify.LoginUserinfo(request);
        SysLogApi log_sysLogApi = new SysLogApi(LogStringUtil.USER, LogStringUtil.SUCCESS, user.getId());

        JSONObject log_content = new JSONObject();

        AjaxCallback ajaxCallback = null;
        boolean flag = true;
        if (Check.checkStringNull(api.getAccount())) {
            ajaxCallback = new AjaxCallback(ModuleCallback.FAILURENO, "账号不能为空");
            flag = false;
            log_content.put(LogStringUtil.CAUSEFAIL, "账号不能为空");
        } else {
            if (Check.checkStringNull(api.getPwd())) {
                ajaxCallback = new AjaxCallback(ModuleCallback.FAILURENO, "密码不能为空");
                flag = false;
                log_content.put(LogStringUtil.CAUSEFAIL, "密码不能为空");
            } else {
                if (Check.checkObjNull(api.getRoid())) {
                    ajaxCallback = new AjaxCallback(ModuleCallback.FAILURENO, "所属角色不能为空");
                    flag = false;
                    log_content.put(LogStringUtil.CAUSEFAIL, "密码不能为空");
                }
            }
        }
        //添加
        if (api.getId() == null) {
            log_sysLogApi.setOperation(LogStringUtil.ADD);
            if (!flag) {
                log_sysLogApi.setStatus(LogStringUtil.FAILURE);
            } else {
                user = new User();
                user.setAccount(api.getAccount());
                user.setStatus(1);
                List<User> list = userService.findByExampleEq(user);
                //账户重复检查
                if (list.size() > 0) {
                    ajaxCallback = new AjaxCallback(ModuleCallback.FAILURENO, "该账户已存在");
                    log_sysLogApi.setStatus(LogStringUtil.FAILURE);
                    log_content.put(LogStringUtil.CAUSEFAIL, "该账户已存在");
                } else {
                    //添加其他属性
                    Date date=new Date();
                    user.setCreatedate(date);
                    user.GeneralParams(api.getUname(), MD5ArithmeticUtils.getMd5(api.getPwd()),api.getMemo(),api.getRoid(),api.getTel(),api.getEmail(), MD5ArithmeticUtils.getMd5(date.toString()+api.getAccount()));
                    userService.insertT(user);
                    log_sysLogApi.setStatus(LogStringUtil.SUCCESS);
                    log_content.put("账号",api.getAccount());
                    log_content.put("用户名",api.getUname());
                    log_content.put("备注",api.getMemo());
                    ajaxCallback = new AjaxCallback(true, ModuleCallback.SUCCESSNO, "用户添加成功");
                }
            }
        }
        //修改
        else {
            log_sysLogApi.setOperation(LogStringUtil.UPDATA);
            if (!flag) {
                log_sysLogApi.setStatus(LogStringUtil.FAILURE);
            } else {
                if ("********".equals(api.getPwd())) {
                    api.setPwd(null);
                }
                User oldUser = userService.get(api.getId());  //数据库中的对应用户
                //用户错误
                if (oldUser == null) {
                    ajaxCallback = new AjaxCallback(ModuleCallback.FAILURENO, "该账户不存在");
                    log_sysLogApi.setStatus(LogStringUtil.FAILURE);
                    log_content.put(LogStringUtil.CAUSEFAIL, "该账户不存在");
                } else {
                    user = new User();
                    user.setAccount(api.getAccount());
                    user.setStatus(1);
                    List<User> list = userService.findByExampleEq(user);
                    if (list.size()!=0&&(list.size()>1||!list.get(0).getId().equals(oldUser.getId()))){
                        ajaxCallback = new AjaxCallback(ModuleCallback.FAILURENO, "账户已存在");
                        log_sysLogApi.setStatus(LogStringUtil.FAILURE);
                        log_content.put(LogStringUtil.CAUSEFAIL, "该账户不存在");
                    } else {
                        oldUser.setName(api.getUname());
                        if (!Check.checkStringNull(api.getPwd()))
                            oldUser.setPwd(MD5ArithmeticUtils.getMd5(api.getPwd()));
                        oldUser.setAccount(api.getAccount());
                        oldUser.setMemo(api.getMemo());
                        oldUser.setRoid(api.getRoid());
                        oldUser.setTel(api.getTel());
                        oldUser.setEmail(api.getEmail());
                        userService.updateT(oldUser);
                        log_sysLogApi.setStatus(LogStringUtil.SUCCESS);
                        log_content.put("账号",api.getAccount());
                        log_content.put("用户名",api.getUname());
                        log_content.put("备注",api.getMemo());
                        ajaxCallback = new AjaxCallback(true, ModuleCallback.SUCCESSNO, "用户修改成功");
                    }
                }
            }
        }
        log_sysLogApi.setContent(log_content);
        syslogService.WriteLog(log_sysLogApi);
        return JSON.toJSONString(ajaxCallback);
    }

    @RequestMapping(value = "/del")
    public String delUserById(@RequestBody DelArr delArr, HttpServletRequest request) {
        AjaxCallback ajaxCallback;
        userService.batchDelete(delArr.getIds());
        JSONObject log_content = new JSONObject();
        log_content.put("用户id",JSON.toJSONString(delArr.getIds()));
        SysLogApi log_sysLogApi = new SysLogApi(LogStringUtil.DEL, LogStringUtil.USER, LogStringUtil.SUCCESS,log_content,webUtilify.LoginUserinfo(request).getId());
        ajaxCallback = new AjaxCallback(ModuleCallback.SUCCESSNO, "删除成功");
        syslogService.WriteLog(log_sysLogApi);
        return JSON.toJSONString(ajaxCallback);
    }

    @RequestMapping(value = "/getUser")
    public String getUserById(@RequestBody UserListApi api, HttpServletRequest request) {
        AjaxCallback ajaxCallback;
        User user = userService.get(api.getId());  //数据库中的对应用户
        //用户错误
        if (user == null) {
            ajaxCallback = new AjaxCallback(ModuleCallback.FAILURENO, "该账户不存在");
            return JSON.toJSONString(ajaxCallback);
        }
        ajaxCallback = new AjaxCallback(ModuleCallback.SUCCESSNO, "请求成功", usertoapi(user));
        return JSON.toJSONString(ajaxCallback);
    }

    @RequestMapping(value = "/getRoleList")
    public String getRoleList(@RequestBody UserListApi api, HttpServletRequest request) {
        List<Role> list = roleService.getList();
        AjaxCallback ajaxCallback = new AjaxCallback(ModuleCallback.SUCCESSNO, "请求成功");
        ajaxCallback.setList(list);
        return JSON.toJSONString(ajaxCallback);
    }

    private UserGetApi usertoapi(User user) {
        UserGetApi api = new UserGetApi();
        api.setId(user.getId());
        api.setAccount(user.getAccount());
        api.setUname(user.getName());
        api.setPwd("********");
        api.setMemo(user.getMemo());
        api.setRoid(user.getRoid());
        api.setRolename(user.getRole().getName());
        api.setTel(user.getTel());
        api.setEmail(user.getEmail());
        return api;
    }

    private List userdbtoapi(List<User> users) {
        List<UserListApi> apis = new ArrayList<>();
        for (User user : users) {
            UserListApi api = new UserListApi();
            api.setId(user.getId());
            api.setAccount(user.getAccount());
            api.setRole(user.getRole().getName());
            api.setEmail(user.getEmail());
            api.setTel(user.getTel());
            api.setUname(user.getName());
            api.setMemo(user.getMemo());
            api.setCreatedate(TimeStampTool.DateToString("yy-MM-dd HH:mm:ss", user.getCreatedate()));
            apis.add(api);
        }
        return apis;
    }
}
